package jrobutt;

import java.io.InputStream;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

public abstract class ResourceLoader<T>
{
    private Map<String, T> data_cache;
    
    private final String get_full_name (String name)
    {
        return "/res/" + name;
    }
    
    public ResourceLoader ()
    {
        data_cache = new HashMap<String, T>();
    }
    
    protected abstract T get_data (InputStream istream) throws IOException;
    
    public T load (String name)
    {
        return load(name, true);
    }
    public T load (String name, boolean cache)
    {
        T cached = data_cache.get(name);
        if (cached != null) return cached;
        
        String full_name = get_full_name(name);
        InputStream istream = ResourceLoader.class.getResourceAsStream(full_name);
        T data;
        try
        {
            data = get_data(istream);
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
            return null;
        }
        if (cache) data_cache.put(name, data);
        
        return data;
    }
}
